import 'package:flutter/material.dart';
import 'package:ichinesereader/controller/strokeOrderAnimation.dart';
import 'package:ichinesereader/utils/helper.dart';
import 'package:ichinesereader/widgets/tools/strokeOrderAnimator.dart';
import 'package:provider/provider.dart';
// import 'package:stroke_order_animator/strokeOrderAnimationController.dart';
// import 'package:stroke_order_animator/strokeOrderAnimator.dart';
import 'package:get/get.dart';
import 'package:http/http.dart' as http;
import 'package:ichinesereader/utils/log.dart';

// ignore: must_be_immutable
class StrokeAnimator extends StatefulWidget {
  StrokeAnimator({Key? key, required this.characters}) : super(key: key);
  String characters = '爱读';

  @override
  _StrokeAnimatorState createState() => _StrokeAnimatorState();
}

class _StrokeAnimatorState extends State<StrokeAnimator>
    with TickerProviderStateMixin {
  PageController? _pageController;
  int _selectedIndex = 0;

  List<StrokeOrderAnimationController> _strokeOrderAnimationControllers = [];

  void fetchWordJson() async {
    try {
      List<String> result = widget.characters.split('');
      for (var word in result)
      //result.forEach((word) async  // foreach
      {
        var encoded = Uri.encodeFull(
            'https://cdn.jsdelivr.net/npm/hanzi-writer-data@2.0/$word.json');
        Uri url = Uri.parse(encoded);
        var response = await http.get(
          url,
        );
        if (response.statusCode == 200) {
          var wordJsonString = response.body;
          if (wordJsonString.isNotEmpty) {
            var strokejson = StrokeOrderAnimationController(
              wordJsonString,
              this,
              onQuizCompleteCallback: (summary) {
                var msg = [
                  "Quiz finished. ".tr,
                  summary.nTotalMistakes.toString(),
                  " mistakes".tr
                ].join();
                showSnackMsg(msg);
              },
            );
            this.setState(() {
              _strokeOrderAnimationControllers.add(strokejson);
            });
          }
        } else {
          throw Exception('Failed to load stroke json');
        }
      }
      //);
    } catch (error) {
      Log.debug(error);
      _strokeOrderAnimationControllers = [
        StrokeOrderAnimationController(
          "{'strokes': ['M 517 808 Q 466 771 334 728 Q 328 719 334 716 Q 358 709 501 742 Q 564 763 615 767 Q 633 766 637 774 Q 641 784 631 796 Q 577 844 543 845 Q 536 842 533 832 Q 532 817 517 808 Z','M 319 634 Q 338 613 358 588 Q 368 575 382 574 Q 392 574 397 585 Q 403 597 398 624 Q 392 648 319 676 Q 306 680 300 679 Q 296 676 295 664 Q 298 654 319 634 Z','M 448 676 Q 481 607 508 600 Q 521 596 531 614 Q 535 627 529 648 Q 522 664 502 676 Q 471 697 457 702 Q 448 705 445 694 Q 442 685 448 676 Z','M 641 701 Q 635 689 574 605 Q 565 589 580 593 Q 626 621 679 664 Q 695 679 715 688 Q 734 698 723 713 Q 711 728 688 739 Q 666 749 656 747 Q 644 746 649 733 Q 653 717 641 701 Z','M 246 511 Q 246 533 221 552 Q 202 567 199 540 Q 205 510 166 459 Q 133 423 135 402 Q 141 369 151 351 Q 167 323 187 352 Q 205 377 217 415 Q 229 452 239 477 L 246 511 Z','M 464 516 Q 710 561 755 551 Q 770 544 768 537 Q 768 533 730 462 Q 723 449 729 445 Q 736 441 753 451 Q 810 487 856 497 Q 895 507 894 516 Q 893 526 823 580 Q 799 601 725 584 Q 614 571 351 526 Q 299 519 246 511 C 216 507 210 484 239 477 Q 261 468 284 474 Q 353 496 428 510 L 464 516 Z','M 460 383 Q 499 392 666 418 Q 676 417 685 430 Q 686 442 663 451 Q 633 475 569 451 Q 527 442 484 430 L 409 414 Q 391 413 374 409 Q 334 403 288 397 Q 260 393 282 376 Q 315 352 346 359 Q 365 365 391 369 L 460 383 Z','M 419 301 Q 437 335 454 369 Q 457 376 460 383 L 484 430 Q 487 437 492 443 Q 505 453 502 468 Q 493 486 464 516 C 444 538 425 540 428 510 Q 435 486 420 441 Q 414 429 410 415 Q 409 415 409 414 L 391 369 Q 312 195 204 106 Q 177 81 151 59 Q 144 55 140 49 Q 134 39 145 38 Q 181 35 284 121 Q 293 131 303 140 Q 345 182 403 273 L 419 301 Z','M 570 131 Q 598 171 620 227 Q 630 260 651 275 Q 667 288 651 304 Q 632 322 602 337 Q 581 347 560 337 Q 502 310 423 302 Q 420 302 419 301 C 389 297 373 277 403 273 Q 425 266 458 275 Q 504 284 551 293 Q 567 299 568 279 Q 568 225 529 161 L 506 130 Q 490 112 471 95 Q 413 52 266 17 Q 250 16 259 6 Q 266 -1 294 0 Q 390 9 446 30 Q 501 52 542 97 L 570 131 Z','M 542 97 Q 675 -36 723 -32 Q 805 -25 872 -9 Q 906 -2 903 8 Q 902 12 866 21 Q 685 61 645 83 Q 620 95 570 131 L 529 161 Q 502 182 476 205 Q 437 239 404 236 Q 388 235 385 230 Q 384 223 399 214 Q 435 198 506 130 L 542 97 Z'],'medians':[[[627,780],[561,797],[461,752],[338,722]],[[304,669],[371,616],[382,590]],[[456,690],[499,644],[512,620]],[[660,736],[679,704],[603,622],[585,612],[583,602]],[[211,545],[221,510],[202,458],[172,402],[168,355]],[[248,481],[264,492],[364,514],[466,532],[475,529],[484,536],[499,534],[554,547],[740,570],[785,564],[809,541],[811,529],[734,451]],[[283,387],[337,380],[604,435],[639,438],[674,432]],[[435,506],[455,489],[463,464],[419,361],[367,263],[321,197],[262,129],[188,70],[148,46]],[[410,275],[433,287],[574,316],[594,305],[607,284],[580,201],[560,162],[528,118],[490,80],[410,39],[354,23],[265,10]],[[391,228],[421,220],[458,198],[586,87],[682,26],[720,11],[898,6]]]}",
          this,
          onQuizCompleteCallback: (summary) {
            var msg = [
              "Quiz finished. ",
              summary.nTotalMistakes.toString(),
              " mistakes"
            ].join();
            showSnackMsg(msg);
          },
        ),
        StrokeOrderAnimationController(
          "{'strokes': ['M 282 735 Q 313 708 345 676 Q 360 660 378 661 Q 391 662 396 677 Q 402 693 392 728 Q 386 750 351 767 Q 267 800 252 791 Q 246 787 248 772 Q 252 759 282 735 Z','M 153 493 Q 104 477 78 475 Q 63 476 61 468 Q 57 461 68 452 Q 107 428 139 442 Q 229 491 241 482 Q 248 476 242 371 Q 239 259 207 155 Q 192 124 234 76 Q 244 64 254 71 Q 261 78 273 101 Q 307 152 381 239 Q 393 251 390 258 Q 389 265 378 256 Q 341 231 305 200 Q 268 167 273 215 Q 273 281 298 442 Q 302 466 323 489 Q 336 499 326 511 Q 316 527 278 544 Q 266 550 249 539 Q 188 505 153 493 Z','M 607 691 Q 555 681 497 676 Q 463 670 487 654 Q 521 633 593 646 Q 599 647 609 648 L 656 657 Q 699 667 746 675 Q 785 684 791 689 Q 800 696 795 704 Q 788 716 760 723 Q 727 729 660 704 L 607 691 Z','M 660 704 Q 661 713 662 720 Q 665 739 668 753 Q 672 763 674 773 Q 677 782 659 795 Q 628 811 607 815 Q 594 819 586 811 Q 579 804 587 791 Q 602 769 607 691 L 609 648 Q 610 603 610 554 C 610 524 646 531 648 561 Q 652 610 656 657 L 660 704 Z','M 610 554 Q 561 547 508 535 Q 468 526 426 521 Q 396 517 416 502 Q 447 477 478 487 Q 587 529 737 547 Q 767 551 777 550 Q 796 541 794 533 Q 782 493 768 450 L 769 449 Q 776 445 790 457 Q 838 493 878 505 Q 911 518 909 525 Q 908 535 841 581 Q 819 596 739 578 Q 670 569 648 561 L 610 554 Z','M 480 412 Q 519 364 539 365 Q 551 364 556 380 Q 557 392 548 409 Q 530 430 483 436 Q 474 437 474 427 Q 473 420 480 412 Z','M 455 328 Q 497 274 519 273 Q 531 272 537 288 Q 538 300 529 317 Q 522 330 502 337 Q 471 350 459 352 Q 450 353 450 343 Q 449 336 455 328 Z','M 638 211 Q 689 224 853 246 Q 863 245 873 258 Q 874 270 851 280 Q 821 301 732 275 Q 698 268 663 257 Q 656 256 649 253 L 599 243 L 412 217 Q 384 213 406 196 Q 418 186 432 178 Q 445 171 467 177 Q 521 190 588 202 L 638 211 Z','M 649 253 Q 656 299 664 370 Q 665 395 676 425 Q 682 435 673 443 Q 625 486 589 476 Q 570 469 585 453 Q 609 426 610 377 Q 610 293 599 243 L 588 202 Q 552 121 463 63 Q 432 47 389 25 Q 377 21 374 17 Q 370 13 384 9 Q 445 5 559 78 Q 578 94 593 112 Q 636 172 638 211 L 649 253 Z','M 694 141 Q 746 95 808 26 Q 824 7 840 2 Q 850 1 857 11 Q 870 24 856 69 Q 846 109 771 143 Q 722 164 694 172 Q 685 178 683 165 Q 683 152 694 141 Z'],'medians':[[[257,783],[350,724],[376,681]],[[71,464],[108,458],[142,465],[234,507],[270,507],[278,497],[245,185],[255,152],[289,163],[384,254]],[[490,666],[546,660],[629,673],[723,697],[783,699]],[[597,802],[634,767],[630,583],[615,562]],[[419,512],[467,505],[666,552],[753,567],[791,567],[821,554],[836,534],[773,454]],[[485,425],[522,401],[539,382]],[[461,341],[499,314],[519,291]],[[407,207],[454,199],[616,226],[785,263],[823,266],[862,260]],[[590,464],[633,435],[639,411],[629,274],[604,177],[579,134],[521,78],[460,42],[380,14]],[[693,161],[802,85],[829,51],[842,19]]]}",
          this,
          onQuizCompleteCallback: (summary) {
            var msg = [
              'Quiz finished. '.tr,
              summary.nTotalMistakes.toString(),
              ' mistakes'.tr
            ].join();
            showSnackMsg(msg);
          },
        ),
      ];
    }
  }

  @override
  void initState() {
    _pageController = PageController();
    fetchWordJson();
    super.initState();
  }

  @override
  void dispose() {
    _pageController?.dispose();
    for (var controller in _strokeOrderAnimationControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Stroke Animator".tr),
      ),
      body: this._strokeOrderAnimationControllers.isNotEmpty
          ? ChangeNotifierProvider<StrokeOrderAnimationController>.value(
              value: _strokeOrderAnimationControllers[_selectedIndex],
              child: Consumer<StrokeOrderAnimationController>(
                  builder: (context, controller, child) {
                return Center(
                  child: SizedBox(
                    width: 500,
                    child: Column(
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.all(12.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              ElevatedButton(
                                  onPressed: () {
                                    if (!controller.isQuizzing)
                                      _pageController?.previousPage(
                                          duration: Duration(milliseconds: 500),
                                          curve: Curves.ease);
                                  },
                                  child: Text("Previous character".tr)),
                              Spacer(),
                              ElevatedButton(
                                  onPressed: () {
                                    if (!controller.isQuizzing)
                                      _pageController?.nextPage(
                                          duration: Duration(milliseconds: 500),
                                          curve: Curves.ease);
                                  },
                                  child: Text("Next character".tr)),
                            ],
                          ),
                        ),
                        // if (GetPlatform.isWeb ||
                        //     GetPlatform.isLinux ||
                        //     GetPlatform.isWindows ||
                        //     GetPlatform.isMacOS)
                        //   _strokeOrderAnimationControllers.length > 1
                        //       ? Padding(
                        //           padding: const EdgeInsets.all(12.0),
                        //           child: Row(
                        //             mainAxisAlignment: MainAxisAlignment.center,
                        //             children: [
                        //               ElevatedButton(
                        //                   onPressed: () {
                        //                     if (!controller.isQuizzing)
                        //                       _pageController?.previousPage(
                        //                           duration: Duration(
                        //                               milliseconds: 500),
                        //                           curve: Curves.ease);
                        //                   },
                        //                   child: Text("Previous character".tr)),
                        //               Spacer(),
                        //               ElevatedButton(
                        //                   onPressed: () {
                        //                     if (!controller.isQuizzing)
                        //                       _pageController?.nextPage(
                        //                           duration: Duration(
                        //                               milliseconds: 500),
                        //                           curve: Curves.ease);
                        //                   },
                        //                   child: Text("Next character".tr)),
                        //             ],
                        //           ),
                        //         )
                        //       : Text(''),
                        Expanded(
                          child: PageView(
                            physics: controller.isQuizzing
                                ? NeverScrollableScrollPhysics()
                                : ScrollPhysics(),
                            controller: _pageController,
                            scrollDirection: Axis.horizontal,
                            children: List.generate(
                              _strokeOrderAnimationControllers.length,
                              (index) => FittedBox(
                                child: StrokeOrderAnimator(
                                  _strokeOrderAnimationControllers[index],
                                  key: UniqueKey(),
                                ),
                              ),
                            ),
                            onPageChanged: (index) => {
                              setState(() {
                                _strokeOrderAnimationControllers[_selectedIndex]
                                    .stopAnimation();
                                _selectedIndex = index;
                              })
                            },
                          ),
                        ),
                        Flexible(
                          child: Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: GridView(
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                childAspectRatio: 3,
                                crossAxisCount: 3,
                                mainAxisSpacing: 10,
                              ),
                              primary: false,
                              children: <Widget>[
                                ElevatedButton(
                                  onPressed: !controller.isQuizzing
                                      ? () {
                                          if (!controller.isAnimating) {
                                            controller.startAnimation();
                                          } else {
                                            controller.stopAnimation();
                                          }
                                        }
                                      : null,
                                  child: controller.isAnimating
                                      ? Text("Stop animation".tr)
                                      : Text("Start animation".tr),
                                ),
                                SizedBox(
                                  width: 18,
                                ),
                                ElevatedButton(
                                  onPressed: () {
                                    if (!controller.isQuizzing) {
                                      controller.startQuiz();
                                    } else {
                                      controller.stopQuiz();
                                    }
                                  },
                                  child: controller.isQuizzing
                                      ? Text("Stop quiz".tr)
                                      : Text("Start quiz".tr),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                );
              }),
            )
          : Center(child: CircularProgressIndicator()),
    );
  }
}
